package com.lstimeline.servlet;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.*;
import javax.servlet.http.*;

import com.lstimeline.utility.DataManager.*;

public class AccountServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	// a hashmap of school ids to schools' names
	private static HashMap<Integer, String> schoolMap;
	
	@SuppressWarnings("unchecked")
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		
		//TODO change it to AccountServletDataManager
		AccountServletDataManager.loadDriver();
		
		//school list should be generated only once
		ServletContext context = getServletContext();
		synchronized(this) {
			if (context.getAttribute("schoolMap") == null) {
				HashMap<Integer, String> schoolMap = ViewDataManager.getSchoolNameMap();
				context.setAttribute("schoolMap", schoolMap);
				//System.out.println("School map created");
			}
			schoolMap = (HashMap<Integer, String>) context.getAttribute("schoolMap");
		}
	}
	
	/**
	 * Redirect unregistered users to login
	 */
	private void redirectToLogin(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
		request.setAttribute("errorMessage", "Please login.");
		RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/login.jspx");
		dispatcher.forward(request, response);
	}
	
	/**
	 * Check whether if the user has logged in
	 */
	private boolean hasLoggedIn(HttpServletRequest request)
		throws ServletException {
		return (request.getSession().getAttribute("userBean") != null);
	}
	
	/**
	 * Get request: handles different action codes
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
		throws ServletException, IOException {
		if(hasLoggedIn(request)) {
			//1. Schools never selected : School selection page
			//2. Schools selected: show latest status + update button
			//3. Other actions based on action parameters (action=logout etc)
		} else {
			redirectToLogin(request, response);
		}
	}
}
